package cn.leedsoft.luma.controller;

import cn.leedsoft.luma.plugins.shiro.ShiroUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by leeds on 2016/6/23 13:42.
 */
@Controller
@RequestMapping("/login")
public class LoginController {
    @RequestMapping(value = "")
    public String showLoginForm(HttpServletRequest req, Model model) {

        String exceptionClassName = (String) req.getAttribute("shiroLoginFailure");

        String error = null;
        if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
            error = "用户名/密码错误";
        } else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
            error = "用户名/密码错误";
        } else if (AuthenticationException.class.getName().equals(exceptionClassName)) {
            error = "用户名/密码错误";//密码为null时会抛此异常
        } else if (ExcessiveAttemptsException.class.getName().equals(exceptionClassName)) {
            error = "用户名密码错误次数超限，请在10分钟后重试";
        } else if (exceptionClassName != null) {
            error = "其他系统错误：" + exceptionClassName;
        }
        if (StringUtils.isNotBlank(error) && StringUtils.isNotBlank(req.getParameter("username")))
            model.addAttribute("username", req.getParameter("username"));
        model.addAttribute("error", error);
        if (ShiroUtils.user()) {
            return "redirect:test.do";
        }
        return "login";
    }
}
